package phone.qyg.com.qyg.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.application.QXApplication;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.OptionImageUtils;
import com.app.utils.PromptManager;
import com.app.utils.ShareOtherUtils;
import com.app.utils.SharePrefUtil;
import com.app.utils.SystemPrintl;
import com.app.utils.TransformController;
import com.app.view.CustomVideoView;
import com.app.view.CustomViewPagerAddCache;
import com.app.view.RatioFrameLayout;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.socialize.ShareAction;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.adapter.FramgmentAdapter;
import phone.qyg.com.qyg.fragment.course.detail.CatalogFragment;
import phone.qyg.com.qyg.fragment.course.detail.InterlocutionFragment;
import phone.qyg.com.qyg.fragment.course.detail.IntroduceFragment;
import phone.qyg.com.qyg.fragment.course.detail.NoteFragment;
import phone.qyg.com.qyg.model.Base;
import phone.qyg.com.qyg.model.CollectionItem;
import phone.qyg.com.qyg.model.CourseDetail;
import phone.qyg.com.qyg.model.CourseVideo;
import phone.qyg.com.qyg.model.Roll;
import phone.qyg.com.qyg.utils.AppHttpRequest;

/**
 * 作者：lblbh on 2017/12/6 10:50
 * 邮箱：lanbuhan@163.com
 * 功能：课程详情
 */
@ContentView(R.layout.course_detail)
public class CourseDetailActivity extends FragmentActivity {

    final  double VIDEO_BL = 1.7778;//视频比例

    String REGIS_COUNT = "已有<font color='#ff6633'>{0}</font>位用户学习";

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.share)
    TextView share;

    @ViewInject(R.id.chollect)
    TextView chollect;

    @ViewInject(R.id.course_play)
    TextView course_play;

    @ViewInject(R.id.full_video)
    TextView full_video;

    @ViewInject(R.id.one_hint)
    View one_hint;

    @ViewInject(R.id.two_hint)
    View two_hint;

    @ViewInject(R.id.there_hint)
    View there_hint;

    @ViewInject(R.id.four_hint)
    View four_hint;

    @ViewInject(R.id.course_regis_count)
    TextView course_regis_count;

    @ViewInject(R.id.course_regis)
    TextView course_regis;

    @ViewInject(R.id.img)
    ImageView img;

    @ViewInject(R.id.introduce)
    LinearLayout introduce;

    @ViewInject(R.id.catalog)
    LinearLayout catalog;

    @ViewInject(R.id.interlocution)
    LinearLayout interlocution;

    @ViewInject(R.id.note)
    LinearLayout note;

    @ViewInject(R.id.title_layout)
    RelativeLayout title_layout;

    @ViewInject(R.id.course_regis_layout)
    RelativeLayout course_regis_layout;

    @ViewInject(R.id.video_view)
    CustomVideoView video_view;

    @ViewInject(R.id.head_frame)
    RatioFrameLayout head_frame;

    @ViewInject(R.id.home_view_pager)
    CustomViewPagerAddCache home_view_pager;

    BroadcastReceiver mNetworkReceiver;

    Timer mCheckPlayingProgressTimer;

    ShareAction mShareAction;

    CourseDetail model;

    Uri mVideoUri;

    int mPlayingPos;

    int mLastLoadLength = -1;//断网/onStop前缓存的位置信息(ms)

    int deltaTime = 2500;

    boolean isTranVideoItem;//预防传递参数 多次

    int id;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        x.view().inject(this);


        Intent intent = getIntent();
        if(intent != null){
            Bundle bundle = intent.getBundleExtra(TransformController.ChangeKEY.INTENT_KEY);
            if(bundle != null){
                Object obj = bundle.getParcelable(TransformController.ChangeKEY.BUNDLE_KEY);

                if(obj instanceof Base){
                    Base base = (Base) obj;
                    id = base.id;
                }else if(obj instanceof CollectionItem){
                    CollectionItem collItem = (CollectionItem) obj;
                    id = collItem.objectId;
                }else if (obj instanceof Roll) {
                    Roll roll = (Roll) obj;
                    id = roll.objectId;
                }
                initData();
            }
        }
    }

    /**
     * 设置数据
     */
    private void initData(){
        if(id == 0)return;

        String courseID = String.valueOf(id);

        List<Fragment> mList = new ArrayList<Fragment>();

        IntroduceFragment introduce = IntroduceFragment.newInstance(courseID);
        CatalogFragment catalog = CatalogFragment.newInstance(courseID);
        InterlocutionFragment interlocu = InterlocutionFragment.newInstance(courseID);
        NoteFragment note = NoteFragment.newInstance(courseID);

        mList.add(introduce);
        mList.add(catalog);
        mList.add(interlocu);
        mList.add(note);
        FramgmentAdapter apadter = new FramgmentAdapter(this.getSupportFragmentManager());
        apadter.setFramgmentList(mList);
        home_view_pager.setAdapter(apadter);

        Map<String,String> map = new HashMap<String,String>();
        map.put(AppHttpKey.TYPE,"0");
        map.put(AppHttpKey.COURSE_ID,courseID);
        AppHttpRequest.httpRequestDefalut(ApplicationConfig.COURSE_DETAIL,
                map,
                new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(isState){
                            if(JSONTool.isStatus(result)){
                                model = JSONTool.jsonDefaluTranClazz(result,null, CourseDetail.class);
                                setData();
                            }else{
                                PromptManager.showToast(JSONTool.errorHint(result));
                            }
                        }
                    }
                });

        isVideoState();
    }


    private void isVideoState(){
        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ApplicationConfig.APP_QX_COURSE);
        BroadcastReceiver mItemViewListClickReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
//                intent.putExtra(TransformController.ChangeKEY.INTENT_KEY,result);
                if(!isTranVideoItem){
                    isTranVideoItem = true;
                    String result = intent.getStringExtra(TransformController.ChangeKEY.INTENT_KEY);
                    SystemPrintl.systemPrintl("我点击视频传递过来的结果是--->>>"+result);
                    CourseVideo courseVideo = JSONTool.requestJSONClazz(result, CourseVideo.class);
                    if(null != courseVideo){
                        if(null == mNetworkReceiver){
                            unregisterNetworkReceiver();
                        }

                        if(video_view.getCurrentPosition() > 1000){
                            video_view.seekTo(0);
                        }

                        play(courseVideo.videoUrl);
                    }
                }
            }
        };
        broadcastManager.registerReceiver(mItemViewListClickReceiver, intentFilter);
    }



    private void setData(){
        if(null == model)return;
        back.setText(CommonUtil.setAttributeText(model.title));
        CommonUtil.setTextViewDrawableDirection(chollect,4,
                (model.isCollection == 0)?
                        R.drawable.title_collect_normal:
                        R.drawable.title_collect_select);

        ImageLoader.getInstance().displayImage(model.fixImgUrl,img, OptionImageUtils.getRectRatio43());
        course_play.setVisibility((model.videoStatus == 0)?View.GONE:View.VISIBLE);
        CommonUtil.textViewSetText(course_regis_count,
                                    MessageFormat.format(REGIS_COUNT,
                                                            String.valueOf(model.regCount)));

        course_regis_layout.setVisibility((model.isReg == 0)?View.VISIBLE:View.GONE);

    }




    @Event(value = {R.id.back,R.id.share,R.id.chollect,R.id.introduce,
                    R.id.catalog,R.id.interlocution,R.id.note,R.id.course_regis,
                    R.id.course_play,R.id.full_video})
    private void backOnClick(View v){
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
            case R.id.share:
                mShareAction  =  ShareOtherUtils.shareTool(CourseDetailActivity.this,
                        model.shareAddress,
                        model.title,
                        model.detailContent,
                        model.fixImgUrl);
                mShareAction.open();
                break;
            case R.id.chollect:
                if(CommonUtil.isRequestStr(SharePrefUtil.getString(SharePrefUtil.KEY.APP_USER,""))){
                    final int isCollection = model.isCollection;
                    AppHttpRequest.collection(model.id, isCollection, "2", model.title, new AppHttpRequest.OnAppHttpListener() {
                        @Override
                        public void onAppHttpState(boolean isState, String result) {
                            if(isState){
                                PromptManager.showToast((isCollection == 0)?R.string.conllection_sucess:R.string.conllection_quit_sucess);
                                model.isCollection = (isCollection == 0) ? 1:0;
                                CommonUtil.setTextViewDrawableDirection(chollect,4,
                                                                        (model.isCollection == 0)?
                                                                                R.drawable.title_collect_normal:
                                                                                R.drawable.title_collect_select);
                            }
                        }
                    });
                }else{
                    TransformController.transformController(QXApplication.getContext(),LoginActivity.class);
                }

                break;
            case R.id.introduce:
                //介绍
                setTitleState(v);
                if (home_view_pager != null)
                    home_view_pager.setCurrentItem(0);
                break;
            case R.id.catalog:
                //目录
                if(model.isReg == 0){
                    PromptManager.showToast(R.string.no_regis_course_hint);
                    return;
                }
                setTitleState(v);
                if (home_view_pager != null)
                    home_view_pager.setCurrentItem(1);

                break;
            case R.id.interlocution:
                //问答
                if(model.isReg == 0){
                    PromptManager.showToast(R.string.no_regis_course_hint);
                    return;
                }
                setTitleState(v);
                if (home_view_pager != null)
                    home_view_pager.setCurrentItem(2);
                break;
            case R.id.note:
                //笔记
                if(model.isReg == 0){
                    PromptManager.showToast(R.string.no_regis_course_hint);
                    return;
                }
                setTitleState(v);
                if (home_view_pager != null)
                    home_view_pager.setCurrentItem(3);
                break;

            case R.id.course_regis:

                if(!CommonUtil.isRequestStr(SharePrefUtil.getString(SharePrefUtil.KEY.APP_USER,""))){
                    TransformController.transformController(QXApplication.getContext(),LoginActivity.class);
                    return;
                }

                //注册学习
                Map<String,String> map = new HashMap<String,String>();
                map.put(AppHttpKey.TYPE,"1");
                map.put(AppHttpKey.COURSE_ID,String.valueOf(id));
                AppHttpRequest.appQuitState(ApplicationConfig.ATTEND_COURSE,
                        map,
                        new AppHttpRequest.OnAppHttpListener() {
                            @Override
                            public void onAppHttpState(boolean isState, String result) {
                                if(isState){
                                    model.isReg = 1;
                                    PromptManager.showToast(R.string.regis_course_sucess);
                                    course_regis_layout.setVisibility(View.GONE);
                                }
                            }
                        });
                break;
            case R.id.course_play:
//                测试视频播放 快慢是否存在问题
//                String testVideo= "http://img.nmge-sports.com:8010/atta/data/train/course/video/2017/12/01/72e90ab8-7370-44a6-9bf1-256160de456e.mp4";
                play(model.videoUrl);
                break;
            case R.id.full_video:
                if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//                    full_video.
                    CommonUtil.setTextViewDrawableDirection(full_video,4,R.drawable.video_fullscreen);
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    CommonUtil.setTextViewDrawableDirection(full_video,4,R.drawable.video_nonfullscreen);
                }
                break;
        }

    }


    private void play(String videoUrl){
        if(!CommonUtil.isRequestStr(videoUrl))return;
        course_play.setVisibility(View.GONE);
        video_view.setVisibility(View.VISIBLE);

        mVideoUri=Uri.parse(videoUrl);

        MediaController mediaController = new MediaController(this);

//        video_view.setVideoURI(mVideoUri);
        video_view.setMediaController(mediaController);
        mediaController.setMediaPlayer(video_view);
        video_view.requestFocus();
//        video_view.start();

        mLastLoadLength = -1;
        mPlayingPos = -1;

        video_view.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                PromptManager.showToast(R.string.course_play_end);
                course_play.setVisibility(View.VISIBLE);
                video_view.setVisibility(View.GONE);
                full_video.setVisibility(View.GONE);

                if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            }

        });

        video_view.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                SystemPrintl.systemPrintl("开始播放视频");
                isTranVideoItem = false;
            }
        });


        video_view.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int what, int i1) {
                SystemPrintl.systemPrintl("我在Error---->>>"+ what +",mPlayingPos = "+mPlayingPos);
                if ( !CommonUtil.isNetWork() ){
                    PromptManager.showToast(R.string.stop_phone);
                } else {
                    restartPlayVideo();
                }

                return true;
            }
        });

        registerNetworkReceiver();
    }

    /**
     * 错误时候使用
     */
    private void restartPlayVideo() {
        //todo 添加 progressBar 体验好点
        if (mCheckPlayingProgressTimer != null) {
            mCheckPlayingProgressTimer.cancel();
            mCheckPlayingProgressTimer = null;
        }
        video_view.setVideoURI(mVideoUri);
        video_view.start();
        video_view.seekTo(mPlayingPos);

        mLastLoadLength = -1;
        mPlayingPos = 0;
    }


    /**
     * 监听网络变化,用于重新缓冲
     */
    private void registerNetworkReceiver() {
        if (mNetworkReceiver == null) {
            mNetworkReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if (action.equalsIgnoreCase(ConnectivityManager.CONNECTIVITY_ACTION)) {
                        doWhenNetworkChange();
                    }
                }
            };
        }
        registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }

    /**
     * 网络播放
     */
    public void doWhenNetworkChange() {

        //保存当前已缓存长度
        int bufferPercentage = video_view.getBufferPercentage();
        mLastLoadLength = bufferPercentage * video_view.getDuration() / 100;
        //这里需要判断 0
        int currentPosition = video_view.getCurrentPosition();
        if (currentPosition > 0) {
            mPlayingPos = currentPosition;
        }

        SystemPrintl.systemPrintl("缓存长度----->>>"+bufferPercentage);

        if (!CommonUtil.isNetWork()&& bufferPercentage < 100) {
            // 监听当前播放位置,在达到缓冲长度前自动停止
            if (mCheckPlayingProgressTimer == null) {
                mCheckPlayingProgressTimer = new Timer();
            }
            mCheckPlayingProgressTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (mPlayingPos >= mLastLoadLength - deltaTime) {
                        video_view.pause();
                    }
                }
            }, 0, 1000);//每秒检测一次
        } else {
            restartPlayVideo();
        }
    }


    private void unregisterNetworkReceiver() {
        if (mNetworkReceiver != null) {
            unregisterReceiver(mNetworkReceiver);
        }
    }


    /**
     * 屏幕横竖屏切换时避免出现window leak的问题
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mShareAction.close();
        if (video_view == null) {
            return;
        }
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {//横屏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().getDecorView().invalidate();
            float height = CommonUtil.getScreentWidth();
            float width = CommonUtil.getScreentHeight();
            head_frame.getLayoutParams().height = (int) width;
            head_frame.getLayoutParams().width = (int) height;
            title_layout.setVisibility(View.GONE);
        } else {
            final WindowManager.LayoutParams attrs = getWindow().getAttributes();
            attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attrs);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            float width = CommonUtil.getScreentWidth();
            float height = (float) (width /VIDEO_BL);
            head_frame.getLayoutParams().height = (int) height;
            head_frame.getLayoutParams().width = (int) width;
            title_layout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //播放网络视频时,需要检测判断网络状态变化
        if (!CommonUtil.isNetWork()) {
            PromptManager.showToast(R.string.network_error);
        } else {
            if (mPlayingPos > 0) {
                video_view.start();
                video_view.seekTo(mPlayingPos);
                mPlayingPos = 0;
                mLastLoadLength = -1;
            }
        }
    }

    @Override
    protected void onPause() {
        mPlayingPos = video_view.getCurrentPosition();
        video_view.pause();
        super.onPause();
    }

    @Override
    protected void onStop() {
        if (video_view.isPlaying() || video_view.canPause()) {
            video_view.stopPlayback();
        }
        mLastLoadLength = 0;
        super.onStop();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCheckPlayingProgressTimer != null) {
            mCheckPlayingProgressTimer.cancel();
            mCheckPlayingProgressTimer = null;
        }

        Window mWindow = getWindow();
        WindowManager.LayoutParams mParams = mWindow.getAttributes();
        mParams.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
        mWindow.setAttributes(mParams);
        unregisterNetworkReceiver();
    }

    @Override
    public void onBackPressed() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            finish();
        }
    }

    private void setTitleState(View view){
        one_hint.setVisibility((view == introduce)?View.VISIBLE:View.GONE);
        two_hint.setVisibility((view == catalog)?View.VISIBLE:View.GONE);
        there_hint.setVisibility((view == interlocution)?View.VISIBLE:View.GONE);
        four_hint.setVisibility((view == note)?View.VISIBLE:View.GONE);
    }
}
